﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using static System.Resources.ResXFileRef;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.Window;

namespace DocConvertor
{
    public partial class Uc_Convertor : UserControl
    {
        public Uc_Convertor()
        {
            InitializeComponent();
        }

        List<OFDFile> fileList = new List<OFDFile>();
        public IConvertor Convertor { get; set; }


        private void Uc_Convertor_Load(object sender, EventArgs e)
        {
            if(Convertor==null) Convertor= new ConvertorPdf();

            cmbSavePath.SelectedIndex = 0;
            cmbSavePath_SelectedIndexChanged(sender, e);

            cmbSaveExtensions.Items.Clear();
            if (!string.IsNullOrWhiteSpace(Convertor.SaveExtensions))
            {
                var ss = Convertor.SaveExtensions.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
                foreach (var s in ss)
                {
                    if (!string.IsNullOrWhiteSpace(s))
                        cmbSaveExtensions.Items.Add(s);
                }
            }
            if (cmbSaveExtensions.Items.Count > 0)
                cmbSaveExtensions.SelectedIndex = 0;
        }

        private Color ConvertColor(Status status)
        {
            switch (status)
            {
                case Status.等待转换:
                    return Color.Black;
                case Status.正在转换:
                    return Color.CadetBlue;
                case Status.转换完成:
                    return Color.LimeGreen;
                case Status.转换失败:
                    return Color.IndianRed;
                default:
                    return Color.Black;
            }
        }

        private void LoadFilesToListView()
        {
            listView1.BeginUpdate();
            listView1.Items.Clear();
            foreach (OFDFile oFDFile in fileList)
            {
                var item = new ListViewItem(oFDFile.FileName);
                item.UseItemStyleForSubItems = false;
                var subItem = new ListViewItem.ListViewSubItem();
                subItem.Text = oFDFile.Status.ToString();
                subItem.ForeColor = ConvertColor(oFDFile.Status);
                item.SubItems.Add(subItem);
                listView1.Items.Add(item);
            }
            listView1.EndUpdate();
        }
        private void listView1_DragEnter(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent(DataFormats.FileDrop))
            {
                e.Effect = DragDropEffects.Move;
            }
            else
            {
                e.Effect = DragDropEffects.None;
            }
        }

        private void listView1_DragDrop(object sender, DragEventArgs e)
        {
            string[] files = (string[])e.Data.GetData(DataFormats.FileDrop);
            foreach (var file in files)
            {
                OFDFile oFDFile = new OFDFile(file);
                fileList.Add(oFDFile);
            }
            LoadFilesToListView();
        }
        private void button1_Click(object sender, EventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog();
            ofd.Filter = Convertor.OpenFilter;// "OFD 文档(*.ofd)|*.ofd";
            ofd.Multiselect = true;
            ofd.CheckFileExists = true;
            var result = ofd.ShowDialog();
            if (result == DialogResult.OK)
            {
                foreach (var file in ofd.FileNames)
                {
                    OFDFile oFDFile = new OFDFile(file);
                    fileList.Add(oFDFile);
                }
                LoadFilesToListView();
            }
        }

        private void button3_Click(object sender, EventArgs e)
        {
            fileList.Clear();
            LoadFilesToListView();
        }

        private void button2_Click(object sender, EventArgs e)
        {
            if (fileList.Count == 0)
            {
                MessageBox.Show("请先添加或拖拽文件！", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            Task.Factory.StartNew(() =>
            {
                bool didSth = false;
                var savePath = "";
                if (cmbSavePath.SelectedIndex > 0) 
                {
                    savePath = txtSavePath.Text;
                }
                try
                {
                    button2.Enabled = button3.Enabled = cmbSaveExtensions.Enabled = false;
                    for (int i = 0; i < fileList.Count; i++)
                    {
                        if (fileList[i].Status == Status.转换完成)
                        {
                            continue;
                        }
                        var item = listView1.Items[i].SubItems[1];
                        try
                        {
                            item.ForeColor = ConvertColor(Status.正在转换);
                            item.Text = Status.正在转换.ToString();
                            fileList[i].Status = Status.正在转换;

                            if (!Convertor.Converter(fileList[i].FileName, cmbSaveExtensions.Text, savePath))
                            {
                                item.ForeColor = ConvertColor(Status.转换失败);
                                item.Text = Status.转换失败.ToString();
                                fileList[i].Status = Status.转换失败;
                            }
                        }
                        catch (Exception ex)
                        {
                            item.ForeColor = ConvertColor(Status.转换失败);
                            item.Text = Status.转换失败.ToString();
                            fileList[i].Status = Status.转换失败;
                            MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            continue;
                        }
                        finally { didSth = true; }
                        item.ForeColor = ConvertColor(Status.转换完成);
                        item.Text = Status.转换完成.ToString();
                        fileList[i].Status = Status.转换完成;
                    }
                    if (!didSth)
                    {
                        MessageBox.Show("当前所有任务已经完成，请添加新的文件或清空重来。", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    }
                }
                catch { }
                button2.Enabled = button3.Enabled = cmbSaveExtensions.Enabled = true;
            });
        }

        private void cmbSavePath_SelectedIndexChanged(object sender, EventArgs e)
        {
            txtSavePath.Visible = cmbSavePath.SelectedIndex == 1;
            button4.Visible = cmbSavePath.SelectedIndex == 1;
        }

        private void button4_Click(object sender, EventArgs e)
        {
            //新建一个FolderBrowserDialog对象
           var FBDialog = new FolderBrowserDialog();
            /*
             * 下面介绍FolderBrowserDialog四个比较重要的属性或方法
             */
            //1、description属性，可以在对话框提供说明、描述、提醒等信息
            FBDialog.Description = "请选择输出的文件夹";

            //2、RootFolder属性，可以设置对话框启动时的根目录,主要为C盘里的文件夹
            //下面Desktop默认打开桌面
            FBDialog.RootFolder = Environment.SpecialFolder.Desktop;

            //3、ShowNewFloderButton属性，是否在对话框中设置”新建文件夹“按钮
            FBDialog.ShowNewFolderButton = true;

            //4、selectedPath属性，比较重要的属性，它是获取你选择的文件夹的路径，当然
            //我们也可以记住我们每次需要打开的路径，可以避免每次都从桌面开始便利

            //开始我们在btn_click()事件外定义一个空的字符串defaultfilePath

            if (txtSavePath.Text != string.Empty)
            {
                //判断defaultfilePath是否为空，defaultfilePath不为空就可以直接赋值给SelectedPath,每次打开都可以到之前选择的位置
                FBDialog.SelectedPath = txtSavePath.Text;
            }
            if (FBDialog.ShowDialog() == DialogResult.OK)
            {
                //空就默认从桌面出发,然后获取点击的路径
                txtSavePath.Text = FBDialog.SelectedPath;
            }
        }

        private void cmbSaveExtensions_SelectedIndexChanged(object sender, EventArgs e)
        {
            foreach (OFDFile oFDFile in fileList)
            {
                oFDFile.Status = Status.等待转换;
            }
            LoadFilesToListView();
        }
    }
}
